- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path513. Find Bottom Left Tree Value.go
61 lines (55 loc) · 1.2 KB
/
513. Find Bottom Left Tree Value.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
typeTreeNode= structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一 DFS
funcfindBottomLeftValue(root*TreeNode) int {
ifroot==nil {
return0
}
res, maxHeight:=0, -1
findBottomLeftValueDFS(root, 0, &res, &maxHeight)
returnres
}
funcfindBottomLeftValueDFS(root*TreeNode, curHeightint, res, maxHeight*int) {
ifcurHeight>*maxHeight&&root.Left==nil&&root.Right==nil {
*maxHeight=curHeight
*res=root.Val
}
ifroot.Left!=nil {
findBottomLeftValueDFS(root.Left, curHeight+1, res, maxHeight)
}
ifroot.Right!=nil {
findBottomLeftValueDFS(root.Right, curHeight+1, res, maxHeight)
}
}
// 解法二 BFS
funcfindBottomLeftValue1(root*TreeNode) int {
queue:= []*TreeNode{root}
forlen(queue) >0 {
next:= []*TreeNode{}
for_, node:=rangequeue {
ifnode.Left!=nil {
next=append(next, node.Left)
}
ifnode.Right!=nil {
next=append(next, node.Right)
}
}
iflen(next) ==0 {
returnqueue[0].Val
}
queue=next
}
return0
}